import React, { useEffect, useRef, useState, useMemo } from 'react';
import { notification, Spin, Modal, Form, Input, Cascader, Upload, message, AutoComplete } from 'antd'
import { InboxOutlined } from '@ant-design/icons';
import { baseURL } from 'src/service/interceptors'

import {
    foodCategory,
    updateResturant,
    searchplace,
} from 'src/api/getData'

function UploadModal(props) {

    const { shopInfo, onOk, onCancel, city, visible } = props;
    const [categorys, setCategorys] = useState()
    const [form] = Form.useForm()
    const [fileList, setFileList] = useState([]);
    const [uploaded, setUploaded] = useState(false)
    const [autoCompleteOption, setAutoCompleteOption] = useState([])
    const [loading, setLoading] = useState(true);

    async function foodCategoryAsync() {
        try {
            const res = await foodCategory()
            const options = res.data.map(item => {
                const option = {
                    value: item.name,
                    label: item.name
                }
                const sub_categories = item.sub_categories
                if (sub_categories && sub_categories.length > 0) {
                    option.children = sub_categories.map(ele => {
                        return {
                            value: ele.name,
                            label: ele.name
                        }
                    })
                }
                return option
            })
            setCategorys(options)
        } catch (error) {

        }
    }

    useEffect(() => {
        if (!city) return
        setLoading(true)
        Promise.all([
            foodCategoryAsync(),
            querySearchAsync(city.name)
        ]).then(() => {
            setLoading(false)
        })
    }, [city])

    const normFile = (e) => {
        console.log('Upload event:', e);
        if (Array.isArray(e)) {
            return e;
        }
        return e && e.fileList;
    }
    async function handleOk() {
        try {
            const values = await form.validateFields()
            const { id, rating, recent_order_num } = shopInfo
            const { address, category, description, image_path, name, phone } = values;
            setLoading(true)
            const res = await updateResturant({
                address,
                category: category.join('/'),
                description,
                id,
                image_path: image_path[0].response.data,
                name,
                phone,
                rating,
                recent_order_num
            })
            setLoading(false)
            if (res.code === 0) {
                message.success('更新店铺信息成功')
                onOk(values)
            }


        } catch (error) {
            console.error(error)
        }
    }

    function handelCancel() {
        onCancel && onCancel()
    }

    const maxsize = 2; //2M

    const uploadOption = {
        name: 'file',
        action: `${baseURL}v1/addimg/shop`,
        size: maxsize, //unit M
        accept: "image/jpeg,image/png",
        multiple: false,
        listType: "picture",
        showUploadList: {
            showRemoveIcon: true,
            removeIcon: " x ",
        },
        showUploadList: false,
        onChange(info) {

            setFileList([info.file]);
            const status = info.file.status;
            info.fileList.forEach(item => {
                item.thumbUrl = '';
            });
            if (status === 'uploading') {
                console.log(info.file, info.fileList);
                setUploaded(true)
            }
            if (status === "removed") {
                setUploaded(false);
                setFileList([])
            }
            if (status === 'done') {
                console.log(`${info.file.name} file uploaded successfully.`);
                setUploaded(true)
            }
            if (status === 'error') {
                notification.error({
                    message: "上传文件失败，请重试"
                });
                setUploaded(false)
            }
        },
        beforeUpload(file) {
            return new Promise((resolve, reject) => {

                if (file.type !== 'image/jpeg') {
                    notification.error({
                        message: "导入格式不正确",
                        duration: 5
                    });
                    return reject(false);
                }

                if (file.size / 1024 > maxsize * 1024) {
                    notification.error({
                        message: "导入文件不能超过" + maxsize + `M`,
                        duration: 5
                    });
                    return reject(false);
                }

                return resolve(true);
            });
        },
        fileList
    }

    async function querySearchAsync(queryString) {
        if (queryString) {
            try {
                const res = await searchplace(city.id, queryString);
                const list = res.data.map(item => {
                    return {
                        ...item,
                        value: item.address
                    };
                })
                setAutoCompleteOption(list)
            } catch (err) {
                console.log(err)
            }
        }
    }

    return <Modal
        title='修改店铺信息'
        visible={visible}
        onOk={handleOk}
        onCancel={handelCancel}
        confirmLoading={loading}
        destroyOnClose
    >
        <Spin spinning={loading}>
            <Form
                form={form}
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
            >
                <Form.Item
                    name='name'
                    label="店铺名称"
                    initialValue={shopInfo.name}
                    rules={[{ required: true, message: '请输入!' }]}
                >
                    <Input placeholder='请输入' />
                </Form.Item>
                <Form.Item
                    name='address'
                    label="详细地址"
                    initialValue={shopInfo.address}
                    rules={[{ required: true, message: '请输入!' }]}
                >
                    <AutoComplete
                        options={autoCompleteOption}
                        onSearch={querySearchAsync}
                        placeholder="control mode"
                    />
                </Form.Item>
                <Form.Item noStyle>
                    当前城市：{city?.name}
                </Form.Item>
                <Form.Item
                    name='description'
                    label="店铺介绍"
                    initialValue={shopInfo.description}
                    rules={[{ required: true, message: '请输入!' }]}
                >
                    <Input placeholder='请输入' />
                </Form.Item>
                <Form.Item
                    name='phone'
                    label="联系电话"
                    initialValue={shopInfo.phone}
                    rules={[{ required: true, message: '请输入!' }]}
                >
                    <Input placeholder='请输入' />
                </Form.Item>
                <Form.Item
                    name='category'
                    label="店铺分类"
                    initialValue={shopInfo.category.split('/')}
                    rules={[{ required: true, message: '请选择!' }]}
                >
                    <Cascader options={categorys} placeholder="请选择" />
                </Form.Item>
                <Form.Item
                    label="商铺图片"
                    name="image_path"
                    valuePropName="fileList"
                    getValueFromEvent={normFile}
                    initialValue={[
                        {
                            response: {
                                data: shopInfo.image_path
                            }
                        }
                    ]}
                    rules={[{ required: true, message: '请上传商铺图片!' }]}
                >
                    <Upload.Dragger
                        {...uploadOption}
                    >
                        {
                            fileList[0]?.response?.data ? <img src={`${baseURL}img/${fileList[0].response.data}`} /> :
                                shopInfo.image_path ? <img src={`${baseURL}img/${shopInfo.image_path}`} /> :
                                    <>
                                        <p className="ant-upload-drag-icon">
                                            <InboxOutlined />
                                        </p>
                                        <p className="ant-upload-text">Click or drag file to this area to upload</p>
                                        <p className="ant-upload-hint">Support for a single or bulk upload.</p>
                                    </>
                        }
                    </Upload.Dragger>
                </Form.Item>
            </Form>
        </Spin>
    </Modal>
}

export default UploadModal